package com.itheima.aop;

import com.itheima.annotation.AutoFill;
import com.itheima.constant.AutoFillConstant;
import com.itheima.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Component
@Aspect
@Slf4j
public class AutoFillAspect {

    @Pointcut(value = "@annotation(com.itheima.annotation.AutoFill)")
    public void pt(){

    }
    @Before("pt()")
    public void autoFill(JoinPoint joinPoint){
        //拿到注解
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        AutoFill autoFill = signature.getMethod().getAnnotation(AutoFill.class);
        //拿到注解的属性 --- 用来判断是添加还是修改
        OperationType operationType = autoFill.value();
        //拿到参数
        Object arg = joinPoint.getArgs()[0];

        try {
            //添加
            if(OperationType.INSERT == operationType){
                Method setCreateDate = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_DATE, LocalDateTime.class);
                Method setUpdateDate = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_DATE, LocalDateTime.class);

                setCreateDate.invoke(arg,LocalDateTime.now());
                setUpdateDate.invoke(arg,LocalDateTime.now());
            }
            //修改
            if(OperationType.UPDATE == operationType){
                Method setUpdateDate = arg.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_DATE, LocalDateTime.class);
                setUpdateDate.invoke(arg,LocalDateTime.now());
            }
        } catch (Exception e) {
            log.error("时间注入异常!");
        }

    }
}
